package com.ajhlp.spring_modules.db.service;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.ajhlp.spring_modules.db.dao.IRoleDao;
import com.ajhlp.spring_modules.db.model.PageBean;
import com.ajhlp.spring_modules.db.model.Role;

public class RoleServiceImpl implements IRoleService {
	
	@Resource
	private IRoleDao roleDao;
	
	

	public IRoleDao getRoleDao() {
		return roleDao;
	}

	public void setRoleDao(IRoleDao roleDao) {
		this.roleDao = roleDao;
	}

	public List<Role> findRoleByPage(PageBean pageBean) {
		// TODO Auto-generated method stub
		return roleDao.findRoleByPage(pageBean);
	}

	public int countRole() {
		// TODO Auto-generated method stub
		return roleDao.countRole();
	}

	public void addRole(Role role) throws Exception {
		// TODO Auto-generated method stub
		try {
			roleDao.addRole(role);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			if(e.getMessage() != null && e.getMessage().toLowerCase().contains("duplicate")){
				throw new RuntimeException("您输入的角色名已存在");
			}else{
				throw e;
			}
		}
	}

	public void updateRole(Role role) throws Exception {
		// TODO Auto-generated method stub
		try {
			roleDao.updateRole(role);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			if(e.getMessage() != null && e.getMessage().toLowerCase().contains("duplicate")){
				throw new RuntimeException("您输入的角色名已存在");
			}else{
				throw e;
			}
		}
	}

	public void deleteRole(int id) {
		// TODO Auto-generated method stub
		roleDao.deleteRole(id);
	}

	public List<Role> findRole(Map<String, Object> condition) {
		// TODO Auto-generated method stub
		Iterator<String> keys = condition.keySet().iterator();
		
		while(keys.hasNext()){
			String key = keys.next();
			if(condition.get(key) != null && condition.get(key) instanceof String){
				String v = (String) condition.get(key);
				if(v.trim().equals("")){
					condition.put(key, null);
				}else{
					condition.put(key, v.trim());
				}
			}
		}
		
		return roleDao.findRole(condition);
	}

}
